<template>
  <div>
    <h1>{{ state.search }}</h1>
    <button @click="handleSearch">改变查询字段</button>
  </div>
</template>
<script>
//引入watchEffect方法
import {reactive, watchEffect} from 'vue'
export default{
  setup(){
    let timer = null //声明一个变量用于接收setTimeout返回
    let state = reactive({
      search: Date.now() //定义search为当前事件戳
    })
    //watchEffect中onInvalidate
    watchEffect((onInvalidate) => {
      console.log('监听查询字段',state.search)
      //模拟一个3秒的异步请求
      timer = setTimeout(() => {
        console.log('模拟接口异步请求，3秒后返回详情信息')
      }, 3000)
      //通过onInvalidate函数清除上一次请求，避免造成资源浪费
      onInvalidate(() => {
        console.log('清除')
        clearInterval(timer);
      })
    })
    //单击事件方法，更新search变量为当前时间戳
    const handleSearch = () => {
      state.search = Date.now()
    }
    return {
      state,
      handleSearch
    }
  }
}
</script>